package com.robotserver.orders.jobs;

import com.robotserver.orders.constant.CacheKey;
import com.robotserver.orders.param.JdOrderSyncParam;
import com.robotserver.orders.param.PddOrderSyncParam;
import com.robotserver.orders.param.TbOrderSyncParam;
import com.robotserver.orders.service.JdOrderService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


/**
 * 京东订单同步JOB
 * @author jianghan
 * @date 2019-11-08 10:06
 */
@Component
public class JdOrderSyncJob {

    private static Logger logger = LoggerFactory.getLogger(JdOrderSyncJob.class);

    @Autowired
    private JdOrderService jdOrderService;
    @Autowired
    private RedissonClient redissonClient;
    @Value("${cluster.group}")
    private String clusterGroup;

    /**
     * 默认是拉京东联盟订单，京佣订单要单独打包，把其他job全部停掉，然后jdOrderService.syncOrder指定京佣key即可
     * 每分钟执行一次拉取订单（时间范围是一个小时）
     */
//    @Scheduled(cron="0 0/1 * * * ?")
    public void execute(){
        logger.debug("JdOrderSyncJob execute.");

        RLock lock = redissonClient.getLock(clusterGroup+"_service_jd_order_sync_lock");
        boolean getlock = false;
        try {
            if (getlock=lock.tryLock(0,1, TimeUnit.MINUTES)) {
                logger.debug("execute right.");
                Long tmptime = System.currentTimeMillis();
                Long end_time = tmptime / 1000;                     //截至时间为当前时间
                Long begin_time = (tmptime - 300000) / 1000;        //起始时间为5分钟前
                JdOrderSyncParam jdOrderSyncParam = new JdOrderSyncParam();
                jdOrderSyncParam.setBegin_time(begin_time);
                jdOrderSyncParam.setEnd_time(end_time);
                jdOrderService.syncOrder(jdOrderSyncParam);
            }else {
                logger.debug("not execute right.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (getlock){
                lock.unlock();
                logger.debug("release lock.");
            }
        }
    }

    /**
     * lucher
     * 生产者-往redis队列当中生产京东联盟
     * 每1分钟秒执行一次查询京东联盟数据,然后保存到redis队列当中，充当生产者角色
     * @author lucher
     * @date 2021-03-09 10:06
     */
//    @Scheduled(cron="0 0/1 * * * ?")
    public void scheduled_jdTokens_producer(){
        logger.info("-----JdOrderSyncJob scheduled_jdTokens_producer  start----");

        RLock lock = redissonClient.getLock("JdOrderSyncJob_scheduled_jdTokens_producer");
        boolean getlock = false;
        try {
            if (getlock=lock.tryLock()) {
                logger.info("---- execute right----");
                Long tmptime = System.currentTimeMillis();
                Long end_time = tmptime / 1000;                     //截至时间为当前时间
                Long begin_time = (tmptime - 300000) / 1000;        //起始时间为5分钟前
                JdOrderSyncParam jdOrderSyncParam = new JdOrderSyncParam();
                jdOrderSyncParam.setBegin_time(begin_time);
                jdOrderSyncParam.setEnd_time(end_time);
                jdOrderSyncParam.setRedisQueueKey(CacheKey.jdPayOrderQueue);
                //调用生产者线程，遍历京东联盟，往redis队列中添加alimmTokens
                logger.info("-------------往redis中推入京东联盟------jdOrderSyncParam=" + jdOrderSyncParam.toString());
                jdOrderService.syncOrder_producer(jdOrderSyncParam);
            }else {
                logger.debug("----not execute right----");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (getlock){
                lock.unlock();
                logger.info("----release lock----");
            }
        }
    }

    /**
     * lucher
     * 消费者-往redis队列当中消费jdTokens
     * 每10秒执行一次定时任务，启动线程从redis队列中获取jdTokens
     * @author lucher
     * @date 2021-03-12 10:06
     */
//    @Scheduled(cron="0/10 * * * * ?")
    public void scheduled_jdTokens_consumer(){
        logger.info("-----JdOrderSyncJob scheduled_jdTokens_consumer  start----");
        //调用消费者线程，遍历redis队列，消费jdTokens
        JdOrderSyncParam jdOrderSyncParam = new JdOrderSyncParam();
        jdOrderSyncParam.setRedisQueueKey(CacheKey.jdPayOrderQueue);
        jdOrderService.syncOrder_consumer(jdOrderSyncParam);
        logger.info("---------------------------消费京东联盟-----------------jdOrderSyncParam=" + jdOrderSyncParam.toString());
    }


    /**
     * 调用工具商拉取订单
     * 每30秒钟执行一次拉取订单（时间范围是3分钟）
     */
//    @Scheduled(cron="0/30 * * * * ?")
    public void scheduled_jdTokens_byAppKey(){
        logger.info("-----JdOrderSyncJob scheduled_jdTokens_byAppKey  start----");
        RLock lock = redissonClient.getLock("JdOrderSyncJob_scheduled_jdTokens_byAppKey");
        boolean getlock = false;
        try {
            if (getlock=lock.tryLock(0,1, TimeUnit.MINUTES)) {
                logger.debug("execute right.");
                Long tmptime = System.currentTimeMillis();
                Long end_time = tmptime / 1000;                     //截至时间为当前时间
                Long begin_time = (tmptime - 300000) / 1000;        //起始时间为5分钟前
                JdOrderSyncParam jdOrderSyncParam = new JdOrderSyncParam();
                jdOrderSyncParam.setBegin_time(begin_time);
                jdOrderSyncParam.setEnd_time(end_time);
                jdOrderService.syncOrder_byAppKey(jdOrderSyncParam);
            }else {
                logger.debug("not execute right.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (getlock){
                lock.unlock();
                logger.debug("release lock.");
            }
        }
    }

}
